﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Lyon
{
    /// <summary>
    /// 深度克隆对象基类
    /// </summary>
    [Serializable]
    public abstract class Cloneable : ICloneable
    {
        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns></returns>
        public virtual object Clone()
        {
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, this);
                    stream.Seek(0L, SeekOrigin.Begin);
                    return formatter.Deserialize(stream);
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException("克隆对象时发生错误。", exception);
            }
        }
        /// <summary>
        /// 克隆
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object Clone(object obj)
        {
            Guard.ArgumentNotNull(obj, "obj");

            if (obj is ICloneable)
                return ((ICloneable)obj).Clone();

            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, obj);
                    stream.Seek(0L, SeekOrigin.Begin);
                    return formatter.Deserialize(stream);
                }
            }
            catch (Exception exception)
            {
                throw new ApplicationException("克隆对象时发生错误。", exception);
            }
        }
    }

 

}
